package com.lgdz.qydevice.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.core.util.CharsetUtil;
import cn.hutool.core.util.HexUtil;
import sun.misc.BASE64Decoder;

public class HexstringToByteUtil {

    public byte[] hexToByte(String hex) {

        /**
         *先去掉16进制字符串的空格
         */
        hex = hex.replace(" ", "");

        /**
         *字节数组长度为16进制字符串长度的一半
         */
        int byteLength = hex.length() / 2;
        byte[] bytes = new byte[byteLength];

        int m = 0;

        int n = 0;

        for (int i = 0; i < byteLength; i++) {

            m = i * 2 + 1;

            n = m + 1;

            int intHex = Integer.decode("0x" + hex.substring(i * 2, m) + hex.substring(m, n));

            bytes[i] = Byte.valueOf((byte) intHex);

        }

        return bytes;

    }


    /**
     * 字符串转为16进制字符串
     */

    public static String str2HexStr(String str) {
        char[] chars = "AA55A364002601FFD4C142313435390CAF".toCharArray();
        System.out.println("chars:"+new String(chars));
        System.out.println(chars[3]);
        StringBuilder sb = new StringBuilder("");
        byte[] bs = str.getBytes();
        int bit;
        for (int i = 0; i < bs.length; i++) {
            bit = (bs[i] & 0x0f0) >> 4;
            sb.append(chars[bit]);
            bit = bs[i] & 0x0f;
            sb.append(chars[bit]);
        }
        System.out.println(sb.toString().trim());
        return sb.toString().trim();
    }

    public  static   String   getHexstringToByteTest(){
        String str = "AA";
        byte []data = new byte[1];
        int aa= 0xAA;
        data[0]=(byte) aa;

        byte base64_data[] = java.util.Base64.getEncoder().encode(data);
        System.out.println(new String(base64_data));
        String hex = HexUtil.encodeHexStr(str, CharsetUtil.CHARSET_UTF_8);
        System.out.println(hex);
        return null;

    }

    //
    public  static  String  getHexstringToByte(){
        //AA5503640022000A D4 A5 41 38 38 38 38 38 39 01 53 52 AF
        //    AA 55 03 64 00 22 00 0A D4 A5 41 38 38 38 38 38 39 01 53 52 AF  正确播报报文
        byte data[] = new byte[]{(byte)0xAA,0x55, (byte) 0x03,(byte) 0x64,(byte)0x00,0x22,(byte)0x00,(byte)0x0A,(byte)0xD4,(byte)0xA5,0x41,0x38,0x38,0x38,(byte)0x38,0x38,0x39,0X01,0X53,0X52,(byte)0xAF};
        //[2, 8, 109, 90, 2, 36, 2, 19, 3]
        //

        byte data1[] = new byte[]{(byte)2,8, (byte) 109,(byte) 90,2,36,2,(byte)19,(byte)3};
        String base64_data1 = Base64.encode(data1);
        System.out.println("21312321===="+base64_data1);


        byte base64_data[] = java.util.Base64.getEncoder().encode(data);

        String encode1 = Base64.encode(data);
        String base64_str = new String(base64_data);
        System.out.println("base64_str:"+base64_str);
        System.out.println("encode1:"+encode1);

        // String encode4 = Base64.encode( "AA55A364002601FFD4C142313435390CAF");
        // System.out.println(encode4);
        return  null;
    }


    /**
     * 该工具是把16进制字符串转为16进制数据
     * @param hex
     * @return
     */
    public static byte[] hexString2Bytes(String hex) {
        if ((hex == null) || (hex.equals(""))){
            return null;
        }
        else if (hex.length()%2 != 0){
            return null;
        }
        else{
            hex = hex.toUpperCase();
            int len = hex.length()/2;
            byte[] b = new byte[len];
            char[] hc = hex.toCharArray();
            for (int i=0; i<len; i++){
                int p=2*i;
                b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p+1]));
            }
            return b;
        }
    }

    /**
     * 该工具是把16进制字符串转为16进制，然后转为base64编码
     * @param hex
     * @return
     */
    public static String hexStringToBytesToBase64(String hex) {
        if ((hex == null) || (hex.equals(""))){
            return null;
        }
        else if (hex.length()%2 != 0){
            return null;
        }
        else{
            hex = hex.toUpperCase();
            int len = hex.length()/2;
            byte[] b = new byte[len];
            char[] hc = hex.toCharArray();
            for (int i=0; i<len; i++){
                int p=2*i;
                b[i] = (byte) (charToByte(hc[p]) << 4 | charToByte(hc[p+1]));
            }
            String encode1 = Base64.encode(b);

            return encode1;
        }
    }



    private static byte charToByte(char c) {
        return (byte) "0123456789ABCDEF".indexOf(c);
    }

    public static String decode(String s) {
        if (s == null)
            return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b,"GBK");
        } catch (Exception e) {
            return null;
        }
    }

    private static final char[] DIGITS
            = {'0', '1', '2', '3', '4', '5', '6', '7',
            '8', '9', 'A', 'B', 'C', 'D', 'E', 'F'};

    public static final String toHex(byte[] data) {
        final StringBuffer sb = new StringBuffer(data.length * 2);
        for (int i = 0; i < data.length; i++) {
            sb.append(DIGITS[(data[i] >>> 4) & 0x0F]);
            sb.append(DIGITS[data[i] & 0x0F]);
        }
        return sb.toString();
    }





    public static void main(String[] args) {
        // System.out.println(HexstringToByteUtil.str2HexStr("AA55A364002601FFD4C142313435390CAF"));

        // byte b = Convert.ToByte(s, 16);
        ////用这个 对接臻识485字符串数据转 base64
    /*        byte[] aa =   HexstringToByteUtil.hexString2Bytes("AA55A364002601FFD4C142313435390CAF");
        String encode1 = Base64.encode(aa);
        System.out.println(encode1);*/

        //getHexstringToByte();
        //  System.out.println( HexstringToByteUtil.decode("AghtWgIkAhMD"));


        /*String guid = "AA55036400";
        byte[] decoded = Base64.decode(guid);
        System.out.println(toHex(decoded));
*/

      /*  //16进制字符串转 base64
        byte[] xx= HexstringToByteUtil.hexString2Bytes("AA5503640022000AD4A541383838383839015352AF");
        String encode1 = Base64.encode(xx);
        System.out.println(encode1);
*/
        //Base64转byte[]，再转16进制字符串
        String guid = "ADQwNDA0OTAwMTExOTIzMTAwMTM1MTI2OUY5MjhEMjdBREMwRTAzMDcwQTcxMzMyMzIz";

        byte[] decoded = java.util.Base64.getDecoder().decode(guid);

        System.out.println(toHex(decoded));



    }
}